package cn.bdqn.controller.user;


import cn.bdqn.pojo.User.User;
import cn.bdqn.service.user.RedisService;
import cn.bdqn.service.user.UserService;
import cn.bdqn.utils.CodeUtil;
import cn.bdqn.utils.Json;
import cn.bdqn.utils.smssendDome;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class SmsCtrlController {
    /***
     * 注入redis模版
     */
    @Autowired
    private RedisService redisService;
    private  String tokenId="TOKEN-USER-";
    @Autowired
    UserService service;

    /**
     * 发送短信
     * @ResponseBody 返回json数据
     * @RequestMapping 拦截请求，指定请求类型：POST
     * @RequestBody 接受前台传入的json数据 接受类型为Map
     * @throws ClientException 抛出异常
     */
    @PostMapping("/smsXxs")
    public Map<String,Object> smsXxs(@RequestBody Map<String,Object> requestMap, HttpServletRequest request) throws ClientException {
        Map<String,Object> map = new HashMap<>();
        String phone = requestMap.get("phoneNumber").toString();
        System.out.println("电话:"+phone);
        // 调用工具栏中生成验证码方法（指定长度的随机数）
        String code = CodeUtil.generateVerifyCode(6);
        //填充验证码
        String TemplateParam = "{\"code\":\""+code+"\"}";
        try {
            smssendDome.sendSMS("http://www.cqhuatang.com", "031775", "VHQ8V9", phone,
                    null, "1603445177114RB0", "尊敬的用户：您的验证码为"+code+"，十分钟内有效，请妥善保管【两江集群创业创新中心】");

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
//        SendSmsResponse response = SmsTool.sendSms(phone,TemplateParam);//传入手机号码及短信模板中的验证码占位符

        map.put("verifyCode",code);
        map.put("phone",phone);
        request.getSession().setAttribute("CodePhone",map);
//        if( response.getCode().equals("OK")) {
            map.put("isOk","OK");
            //验证码绑定手机号并存储到redis
            redisService.set(tokenId+phone,code);
            redisService.expire(tokenId+phone,620);//调用reids工具类中存储方法设置超时时间
//        }
        return map;
    }


    /**
     * 注册验证
     * @ResponseBody 返回json数据
     * @RequestMapping 拦截请求，指定请求类型：POST
     * @RequestBody 接受前台传入的json数据 接受类型为Map
     * @throws ClientException 抛出异常
     */
    @PostMapping("/validateNum")
    public Json validateNum(@RequestBody Map<String,Object> requestMap) throws ClientException {
        String phone = requestMap.get("phone").toString();//获取注册手机号码
        String verifyCode = requestMap.get("verifyCode").toString();//获取手机验证码
        //首先比对验证码是否失效
        String redisauthcode= redisService.get(tokenId+phone); //传入tonkenId返回redis中的value
        Json json=new Json();
        if(StringUtils.isEmpty(redisauthcode)){
            //如果未取到则过期验证码已失效
            json.setCode(404);
        }else  if(!"".equals(redisauthcode)&&!verifyCode.equals(redisauthcode)){
            //验证码错误
            json.setCode(500);
        }else{
            //用户注册成功
            User user = service.loginByPhone(phone);
            if(user!=null){
                json.setCode(200);
                redisService.remove(tokenId+phone);
            }else{
               json.setCode(400);
            }
        }
        return json;
    }

}
